window.onload = () => {
  function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); // 匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; // 返回参数值
  }
  const target = getUrlParam("target");
  const client = getUrlParam("client");
  const token = getUrlParam("token");

  function obj2queryStr(obj) {
    return (
      "?" +
      Object.keys(obj)
        .map((key) => key + "=" + obj[key])
        .join("&")
    );
  }
  const infoContainer = document.getElementById("info");
  fetch("/auth/token" + obj2queryStr({ target, client }), {
    headers: {
      Authorization: "Bearer " + token,
    },
  })
    .then((response) => {
      if (!response.ok) throw response;
      return response;
    })
    .catch((_) => {
      infoContainer.innerText = "登录失败，";
      const a = document.createElement("a");
      a.href = "/";
      a.innerText = "点击回主页";
      infoContainer.append(a);
    })
    .then((response) => response.json())
    .then((result) => {
      infoContainer.innerText = "登录成功，正在跳转...";
      const appToken = result.data.token;
      const appRefreshToken = result.data.refreshToken;
      window.localStorage.setItem(client + "-token", appToken);
      window.localStorage.setItem(client + "-refreshtoken", appRefreshToken);
      window.location.href = decodeURIComponent(target);
    });
};
